<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\ContactStage\Action\Dashboard;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Utils\Codec\Json;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\App\WorkContact\Contract\WorkContactContract;
use MoChat\App\WorkContact\Contract\WorkContactTagContract;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\ContactStage\Contract\ContactStageContract;
use MoChat\Plugin\ContactStage\Contract\ContactStageEmployeeContract;
use MoChat\Plugin\ContactStage\Logic\IndexLogic;

/**
 * 客户阶段管理.
 *
 * Class Index.
 * @Controller
 */
class StageIndex extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var ContactStageContract
     */
    protected $contactStageService;

    /**
     * @Inject
     * @var WorkContactTagContract
     */
    protected $workContactTagService;

    /**
     * @Inject
     * @var IndexLogic
     */
    protected $indexLogic;

    /**
     * 客户 - 阶段关联.
     * @Inject
     * @var ContactStageEmployeeContract
     */
    private $contactStageEmployeeService;

    /**
     * 客户表.
     * @Inject
     * @var WorkContactContract
     */
    private $workContactService;

    /**
     * @RequestMapping(path="/dashboard/contactStage/stageIndex", methods="GET")
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @return array 返回数组
     */
    public function handle(): array
    {
        $user = user();

        // 接收参数
        $params = [
            'type' => (int) $this->request->input('type', 1),
            'stageId' => 0,
            'employeeId' => (int) $this->request->input('employeeId', 0),
            'name' => $this->request->input('name'),
            'startTime' => $this->request->input('startTime'),
            'endTime' => $this->request->input('endTime'),
            'followStartTime' => $this->request->input('followStartTime'),
            'followEndTime' => $this->request->input('followEndTime'),
            'page' => $this->request->input('page', 1),
            'perPage' => $this->request->input('perPage', '10'),
        ];
        $stages = $this->contactStageService->getContactStagesByCorpId($user['corpIds'][0], ['id', 'name', 'description', 'order', 'auto_attribute', 'remind_attribute']);

        if ($params['type'] === 2) {
            $total = 0;
            foreach ($stages as &$item) {
                $params['stageId'] = $item['id'];
                $contactList = $this->indexLogic->handle($params);
                $item['contactList'] = $contactList;
                $total += $contactList['page']['total'];
            }
            unset($item);
        }

//        return ['total' => $total, 'list' => $stages];
        foreach ($stages as &$val) {
            $val['autoAttribute'] = Json::decode($val['autoAttribute']);
            $val['remindAttribute'] = Json::decode($val['remindAttribute']);
            $val['autoAttributeCnt'] = empty($val['autoAttribute']) ? 0 : count($val['autoAttribute']);

            foreach ($val['autoAttribute'] as &$auto) {
                foreach ($auto as &$val3) {
                    $val3['typeName'] = $this->typeName((int) $val3['type']);
                    $val3['conditionName'] = $this->conditionName((int) $val3['type'], $val3['condition'], $stages);
                    $val3['queryTypeName'] = $this->queryTypeName((int) $val3['queryType']);
                }
                unset($val3);
            }
            unset($auto);
        }
        unset($val);

        return $stages;
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [];
    }

    private function typeName(int $type): string
    {
        $typeName = ['客户阶段', '流失状态', '客户标签'];
        return $typeName[$type];
    }

    private function conditionName(int $type, $condition, array $stages)
    {
        if ($type === 0) {// 客户阶段
            foreach ($stages as $stage) {
                if ($stage['id'] === (int) $condition) {
                    return $stage['name'];
                }
            }
        }
        if ($type === 1) {
            $loss = ['未流失', '已流失'];
            return $loss[$condition];
        }
        if ($type === 2) {
            $tags = $this->workContactTagService->getWorkContactTagsById($condition, ['name']);
            return empty($tags) ? [] : array_column($tags, 'name');
        }
        return [];
    }

    private function queryTypeName(int $queryType): string
    {
        $queryTypeName = ['', '且', '或'];
        return $queryTypeName[$queryType];
    }
}
